/* eslint-disable no-console */
// ================================ 切换壁纸 ================================
(async function ($) {

    const $wallpaper = $('.wallpaper');

    // 配置部分
    const BACKGROUND_DIR = $wallpaper.data('bg-dir');
    const BACKGROUND_DEFAULT_DIR = `${BACKGROUND_DIR}default/`;
    const FALLBACK_BACKGROUNDS = [
        `${BACKGROUND_DEFAULT_DIR}bg-grass.jpg`,
        `${BACKGROUND_DEFAULT_DIR}bg-cdlbxx.jpg`,
    ];

    // 初始化变量
    const $windmill = $('#windmill');
    let currentBgIndex = 0;
    let isRotating = false;
    let isHovering = false;
    let hoverAnimationId = null;
    let clickAnimationId = null;
    let currentRotation = 0;
    let backgrounds = [];

    /*
     * 动态检测壁纸图片
     * @return {Promise<string[]>} 可用的壁纸图片路径数组
     */
    async function detectBackgroundImages() {
        const systemImages = await getDefaultBackgroundImages();
        const userImages = await window.AppUtils.getBgUrls();
        const knownImages = systemImages.concat(userImages);
        return knownImages.length > 0 ? knownImages : FALLBACK_BACKGROUNDS;
    }

    /*
     * 获取默认壁纸图片
     * @return {Promise<string[]>} 默认壁纸图片路径数组
     */
    // 获取 default 目录下所有图片作为备用
    async function getDefaultBackgroundImages() {
        try {
            const response = await fetch('/bg-list.json');
            if (response.ok) {
                const images = await response.json();
                const imagesArray = images.images || [];
                return imagesArray.map(item => item.url);
            }
        } catch (e) {
            console.error('[module] 获取默认壁纸图失败:', e);
        }

        // 终极回退方案
        return FALLBACK_BACKGROUNDS;
    }

    /*
     * 预加载壁纸图片
     * @param {number} index - 要预加载的壁纸图片索引
     */
    function preloadBackground(index) {
        // 创建一个隐藏的<img>元素
        const img = new Image();
        // 设置src后，浏览器会默默加载图片
        img.src = backgrounds[index];
        return img;
    }

    /*
     * 应用壁纸图片
     * @param {number} index - 要应用的壁纸图片索引
     */
    function applyBackground(bgUrl) {
        const dark = window.AppUtils.getUserSettings()?.colorTheme === 'dark' || false;
        // 如果 bgUrl 为空，则使用对应风格模式的默认壁纸, 并更新数据库
        if (!bgUrl.length) {
            bgUrl = dark ===true? FALLBACK_BACKGROUNDS[0]: FALLBACK_BACKGROUNDS[1]
            window.__cacheManager.setConfig('image','currentBackground',{
                url: bgUrl,
                updateTime: window.AppUtils.formatDateTime(),
                remark: '设置默认壁纸',
            }).catch(err => console.error('[module] 壁纸设置失败:', err));
        }
        window.AppUtils.setBgImage(bgUrl, true);
    }

    /*
     * 从本地存储读取壁纸索引
     */
    async function loadBackgroundUrl() {
        try {
            let bgUrl = await window.AppUtils.getCurrentBgUrl();
            const urls = await window.AppUtils.getBgUrls();
            const wallpaperExist = urls && urls.length > 0 && urls.includes(bgUrl);
            // 如果本地存储的壁纸不存在且当前壁纸为用户上传壁纸时，才返回空值
            if (!wallpaperExist && bgUrl.startsWith('data:image/')) {
                bgUrl = "";
            }
            return bgUrl;
        } catch (err) {
            console.error('[module] 加载壁纸URL失败:', err);
            return "";
        }
    }

    // 壁纸切换系统
    const wallpaperSystem = {
        shuffledIndices: [],
        currentPos: 0,

        reset() {
            // 使用 Array.from 创建数组，符合 unicorn/no-new-array 规则
            this.shuffledIndices = Array.from(
                { length: backgrounds.length },
                (_, i) => i
            );

            // Fisher-Yates 洗牌算法
            for (let i = this.shuffledIndices.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [this.shuffledIndices[i], this.shuffledIndices[j]] =
                    [this.shuffledIndices[j], this.shuffledIndices[i]];
            }
            this.currentPos = 0;
            console.debug('[module] 洗牌后的索引:', this.shuffledIndices, this.currentPos);
        },

        getRandomIndex(currentIndex) {
            if (backgrounds.length <= 1) return 0;

            // 重新洗牌条件
            if (this.currentPos >= this.shuffledIndices.length) {
                this.reset();
            }

            // 获取下一个索引
            let nextIndex = this.shuffledIndices[this.currentPos++];

            // 跳过当前显示的壁纸
            if (nextIndex === currentIndex && this.currentPos < this.shuffledIndices.length) {
                nextIndex = this.shuffledIndices[this.currentPos++];
            }

            return nextIndex;
        }
    };

    // 更新风车变换样式
    function updateWindmillTransform(scale = 1, rotate = 0) {
        $windmill.css('transform', `scale(${scale}) rotate(${rotate}deg)`);
    }

    // 悬停动画
    function startHoverAnimation() {
        if (hoverAnimationId || isRotating) return;

        let startTime = null;
        const duration = 200; // 动画持续时间(ms)
        const targetScale = 1.1;
        const targetRotate = 15;

        function animateHover(timestamp) {
            if (!startTime) startTime = timestamp;
            const elapsed = timestamp - startTime;
            const progress = Math.min(elapsed / duration, 1);

            const currentScale = 1 + (targetScale - 1) * progress;
            const currentRotate = targetRotate * progress;

            updateWindmillTransform(currentScale, currentRotate);

            if (progress < 1) {
                hoverAnimationId = requestAnimationFrame(animateHover);
            } else {
                hoverAnimationId = null;
            }
        }

        hoverAnimationId = requestAnimationFrame(animateHover);
    }

    // 停止悬停动画
    function stopHoverAnimation() {
        if (hoverAnimationId) {
            cancelAnimationFrame(hoverAnimationId);
            hoverAnimationId = null;
        }

        if (isRotating) return;

        let startTime = null;
        const duration = 200;
        // eslint-disable-next-line regexp/no-empty-character-class
        const startScale = Number.parseFloat($windmill.css('transform').match(/[]/)?.[1] || 1);
        // eslint-disable-next-line regexp/no-empty-character-class
        const startRotate = Number.parseFloat($windmill.css('transform').match(/[]/)?.[1] || 0);

        function animateReturn(timestamp) {
            if (!startTime) startTime = timestamp;
            const elapsed = timestamp - startTime;
            const progress = Math.min(elapsed / duration, 1);

            const currentScale = startScale - (startScale - 1) * progress;
            const currentRotate = startRotate - startRotate * progress;

            updateWindmillTransform(currentScale, currentRotate);

            if (progress < 1) {
                requestAnimationFrame(animateReturn);
            }
        }

        requestAnimationFrame(animateReturn);
    }

    // 点击旋转动画
    function startClickAnimation() {
        if (clickAnimationId) return;

        const startTime = performance.now();
        const duration = 2000; // 旋转持续时间(ms)
        const startScale = 1.1;

        function animateClick(timestamp) {
            const elapsed = timestamp - startTime;
            const progress = (elapsed % duration) / duration;

            currentRotation = progress * 360;
            updateWindmillTransform(startScale, currentRotation);

            if (isRotating) {
                clickAnimationId = requestAnimationFrame(animateClick);
            } else {
                clickAnimationId = null;
            }
        }

        clickAnimationId = requestAnimationFrame(animateClick);
    }

    // 停止点击动画
    function stopClickAnimation() {
        if (clickAnimationId) {
            cancelAnimationFrame(clickAnimationId);
            clickAnimationId = null;
        }
    }

    // 切换壁纸图片（带随机模式）
    function changeBackgroundImage(randomMode = true) {
        // 获取新壁纸索引
        currentBgIndex = randomMode ?
            wallpaperSystem.getRandomIndex(currentBgIndex) :
            (currentBgIndex + 1) % backgrounds.length;

        let nextBg = backgrounds[currentBgIndex];
        const currentBgUrl = new URL(window.AppUtils.extractBase64Url($('.wallpaper').css('background-image'))).pathname;
        // 如果随机第一张壁纸就是页面刷新后的壁纸则取下一张
        if (nextBg === currentBgUrl) nextBg = currentBgIndex + 1 === backgrounds.length? backgrounds[0]: backgrounds[currentBgIndex + 1]
        // 加载新壁纸
        const bgImage = preloadBackground(currentBgIndex)

        bgImage.onload = function () {
            // 淡出当前壁纸
            $wallpaper.animate({opacity: 0.7}, 300, function () {
                // 切换壁纸
                window.AppUtils.setBgImage(nextBg, true);

                // 淡入新壁纸
                $(this).animate({opacity: 1}, 300, () => {
                    // 停止旋转
                    isRotating = false;
                    stopClickAnimation();

                    // 如果鼠标仍在悬停状态，恢复悬停效果
                    if (isHovering) {
                        updateWindmillTransform(1.1, 15);
                    } else {
                        updateWindmillTransform(1, 0);
                    }
                });
            });
        };

        bgImage.onerror = function () {
            isRotating = false;
            stopClickAnimation();
            console.error('[module] 壁纸图片加载失败:', nextBg);
        };
    }

    // 事件绑定
    $windmill.on({
        mouseenter() {
            isHovering = true;
            startHoverAnimation();
        },
        mouseleave() {
            isHovering = false;
            stopHoverAnimation();
            if (!isRotating) {
                updateWindmillTransform(1, 0);
            }
        },
        click() {
            // console.debug('点击风车');
            if (isRotating) {
                // 如果正在旋转，停止旋转
                isRotating = false;
                stopClickAnimation();
                if (isHovering) {
                    updateWindmillTransform(1.1, 15);
                } else {
                    updateWindmillTransform(1, 0);
                }
            } else {
                // 开始旋转
                isRotating = true;
                stopHoverAnimation();
                startClickAnimation();
                changeBackgroundImage(true);
            }
        }
    });

    /**
     * 检查并清理无效的图片URL（非data:image/开头）
     * @returns {Promise<number>} 返回被清理的URL数量
     */
    async function validateAndCleanBackgrounds() {
        const logPrefix = '[selfCheck]';
        try {
            // 1. 获取当前背景数据
            const originalUrls = await window.AppUtils.getBgUrls();
            if (originalUrls.length === 0) return 0;

            // 2. 过滤无效URL
            const validUrls = originalUrls.filter(url => {
                const isDataImage = url.startsWith('data:image/');
                if (!isDataImage) {
                    console.warn(`${logPrefix} 移除无效URL:`, url.substring(0, 50) + (url.length > 50 ? '...' : ''));
                }
                return isDataImage;
            });

            // 3. 检查是否有变动
            const removedCount = originalUrls.length - validUrls.length;
            if (removedCount === 0) {
                console.debug(`${logPrefix} 所有壁纸 URL 格式正确`);
                return 0;
            }

            // 4. 如果变动则更新数据库
            if (removedCount !== 0) {
                await window.__cacheManager.setConfig('image','backgroundCollection',{
                    urls: validUrls,
                    updateTime: window.AppUtils.formatDateTime(),
                    remark: `${logPrefix} 清理了 ${removedCount} 个无效URL`
                });
            }

            console.warn(`${logPrefix} 壁纸清理完成，移除了 ${removedCount} 个无效URL`);
            return removedCount;
        }
        catch (error) {
            console.error(`${logPrefix} 移除无效壁纸URL失败:`, error);
        }
    }

    /*
     * 初始化壁纸系统
     */
    async function initBackgroundSystem() {
        backgrounds = await detectBackgroundImages();
        console.debug(`[systemInfo] 当前有${backgrounds.length}张壁纸`);
        let currentBgUrl = await loadBackgroundUrl();
        if (currentBgUrl && !currentBgUrl.length > 0 && backgrounds.length > 0 ) {
            currentBgUrl = backgrounds[wallpaperSystem.getRandomIndex(-1)];
        }
        preloadBackground(currentBgIndex);
        applyBackground(currentBgUrl);
    }

    // 初始化
    await validateAndCleanBackgrounds();
    await initBackgroundSystem();
})(window.jQuery);